package com.freemalll.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemalll.merchant.constant.ConfigConstant;
import com.freemalll.merchant.service.FaceHelperService;
import com.freemalll.merchant.utils.ConfigUtil;
import org.apache.commons.codec.CharEncoding;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.UnsupportedCharsetException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FaceHelperServiceImpl implements FaceHelperService {


    /**
     * 初始化face++相关接口数据
     *
     * @return
     */
    public JSONObject getFaceParamInit() {
        String coValue = ConfigUtil.getCoValue(ConfigConstant.FACE_CONFIG);
        return JSON.parseObject(coValue);
    }


    /**
     * 身份证ocr识别
     *
     * @param face
     * @return
     */
    @Override
    public JSONObject ocrIdCard(InputStream face) {
        JSONObject config = getFaceParamInit();
        Map<String, Object> params = new HashMap<>();
        //身份证正反面识别
        params.put("api_key", config.getString("appKey"));
        params.put("api_secret", config.getString("appSecret"));
        params.put("image", face);
        String url = config.getString("ocridcard");
        String result = this.sendPostTwo(url, params);
        return JSON.parseObject(result);
    }


    public String sendPostTwo(String url, Map<String, Object> param) {
        // 实例化httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 实例化post方法
        HttpPost httpPost = new HttpPost(url);
        // 结果
        CloseableHttpResponse response = null;
        String content = null;
        try {
            // 提交的参数
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (String key : param.keySet()) {
                if (param.get(key) instanceof File) {
                    builder.addPart(key, new FileBody((File) param.get(key)));
                } else if (param.get(key) instanceof InputStream) {
                    builder.addPart(key, new InputStreamBody((InputStream) param.get(key), UUID.randomUUID() + ".jpeg"));
                } else {
                    builder.addPart(key, new StringBody(param.get(key).toString()));
                }
            }
            httpPost.setEntity(builder.build());

            try {
                response = httpclient.execute(httpPost);
            } catch (IOException e) {
                throw new RuntimeException("ocr识别失败");
            }
            int httpStatus = response.getStatusLine().getStatusCode();
            content = EntityUtils.toString(response.getEntity());
            if (httpStatus == 200) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content;
    }

    /**
     * 开户许可证等识别
     *
     * @param image
     * @return
     */
    @Override
    public JSONObject ocrBankAccount(String image) throws IOException {
        JSONObject config = getFaceParamInit();
        Map<String, Object> params = new HashMap<>();
        //商户开户许可证识别
        String authorization = config.getString("Authorization");
        params.put("url", image);
        BasicHeader header = new BasicHeader("Authorization", authorization);
        String url = config.getString("bankAccount");
        String data = this.sendPostJson(url, JSON.toJSONString(params), header);
        return JSON.parseObject(data);
    }

    /**
     * 营业执照识别
     *
     * @param image
     * @return
     */
    @Override
    public JSONObject ocrBusinessLicense(String image) throws IOException {
        JSONObject config = getFaceParamInit();
        Map<String, Object> params = new HashMap<>();
        //商户开户许可证识别
        String authorization = config.getString("Authorization");
        params.put("url", image);
        BasicHeader header = new BasicHeader("Authorization", authorization);
        String url = config.getString("RecognizeBusinessLicense");
        String result = this.sendPostJson(url, JSON.toJSONString(params), header);
        return JSON.parseObject(result);
    }


    /**
     * 发送json格式的post请求
     *
     * @param url  访问地址
     * @param json 请求参数(json字符串)
     * @return
     * @throws ParseException
     * @throws IOException
     */
    private String sendPostJson(String url, String json, Header... headers) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(json, CharEncoding.UTF_8);
            entity.setContentEncoding(CharEncoding.UTF_8);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpPost.setHeaders(headers);
            httpPost.setHeader("Content-Encoding", CharEncoding.UTF_8);
            httpPost.setHeader("content-type", "application/json");
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        } catch (UnsupportedCharsetException e) {
            throw new RuntimeException(e);
        }
    }


}
